#include <vector>
#include <iostream>
#include <queue>
#include <algorithm>

using namespace std;
using ll = long long;

static const ll INF = (ll)4e18;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int T;
    cin >> T;
    while(T--){
        int N, M;
        cin >> N >> M;
        vector<vector<int>> adj(N+1);
        for(int i = 0; i < M; i++){
            int u, v;
            cin >> u >> v;
            adj[u].push_back(v);
            adj[v].push_back(u);
        }

        vector<char> vis1(N+1, 0), visN(N+1, 0);
        queue<int> q;

        vis1[1] = 1;
        q.push(1);
        while(!q.empty()){
            int u = q.front(); q.pop();
            for(int v: adj[u]){
                if(!vis1[v]){
                    vis1[v] = 1;
                    q.push(v);
                }
            }
        }

        visN[N] = 1;
        q.push(N);
        while(!q.empty()){
            int u = q.front(); q.pop();
            for(int v: adj[u]){
                if(!visN[v]){
                    visN[v] = 1;
                    q.push(v);
                }
            }
        }

        if(vis1[N]){
            cout << 0 << "\n";
            continue;
        }

        vector<int> S, Tset;
        S.reserve(N);
        Tset.reserve(N);
        for(int i = 1; i <= N; i++){
            if(vis1[i]) S.push_back(i);
            if(visN[i]) Tset.push_back(i);
        }
        sort(S.begin(), S.end());
        sort(Tset.begin(), Tset.end());

        vector<ll> dist1(N+1, INF), distN(N+1, INF);
        {
            int j = 0;
            for(int w = 1; w <= N; w++){
                while(j+1 < (int)S.size() &&
                      llabs((ll)S[j+1] - w) <= llabs((ll)S[j] - w))
                {
                    j++;
                }
                ll d = ll(S[j] - w);
                dist1[w] = d*d;
            }
        }

        {
            int j = 0;
            for(int w = 1; w <= N; w++){
                while(j+1 < (int)Tset.size() &&
                      llabs((ll)Tset[j+1] - w) <= llabs((ll)Tset[j] - w))
                {
                    j++;
                }
                ll d = ll(Tset[j] - w);
                distN[w] = d*d;
            }
        }

        ll ans = INF;
        for(int w = 1; w <= N; w++){
            ans = min(ans, dist1[w] + distN[w]);
        }

        cout << ans << "\n";
    }
}
